package cn.edu.java.thread.锁;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockDemo {
    private static ReentrantLock lock = new ReentrantLock();


    public static void main(String[] args) {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                lock.lock(); // 获取锁
                try {
                    System.out.println("线程 " + Thread.currentThread().getName() + " 获取了锁");
                    // 模拟线程执行一段任务
                    for (int i = 0; i < 5; i++) {
                        System.out.println("线程 " + Thread.currentThread().getName() + ": " + i);
                    }
                } finally {
                    lock.unlock(); // 释放锁
                    System.out.println("线程 " + Thread.currentThread().getName() + " 释放了锁");
                }
            }
        };

        // 创建并启动两个线程
        new Thread(runnable).start();
        new Thread(runnable).start();
    }

}

